package com.cn.aam.checaiduo.ui.me;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cn.aam.checaiduo.AppData;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestListener;
import com.cn.aam.checaiduo.backend.observer.OnRequestV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.bean.AgreementB;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.bean.me.InvestOrderDetailB;
import com.cn.aam.checaiduo.bean.me.RedirectContentB;
import com.cn.aam.checaiduo.center.CustomDialogCenter;
import com.cn.aam.checaiduo.ui.homepage.pay.PayActivity;
import com.cn.aam.checaiduo.ui.me.fragment.InvestRecordFragment;
import com.cn.aam.checaiduo.ui.product.ProductDetailActivity;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.utils.StringUtil;
import com.cn.aam.checaiduo.widget.WMToast;
import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * monker on 2017/5/31.
 */

public class InvestRecordDetailActivity extends BaseActivity {


    @BindView(R.id.detail_tv_orderCode)
    TextView tvOrderCode;//订单号
    @BindView(R.id.detail_tv_title)
    TextView tvTitle;//标题
    @BindView(R.id.detail_iv_image)
    ImageView ivImage;//图片
    @BindView(R.id.detail_tv_principal)
    TextView tvPrincipal;//投资本金

    @BindView(R.id.detail_tv_payment)
    TextView tvPayment;//回款金额
    @BindView(R.id.detail_ll_payment)
    LinearLayout llPayment;

    @BindView(R.id.detail_tv_paydate)
    TextView tvPaydate;//付款时间
    @BindView(R.id.detail_tv_paymentdate)
    TextView tvPaymentdate;

    @BindView(R.id.detail_ll_paymentdate)
    LinearLayout llPaymentdate;//回款时间
    @BindView(R.id.detail_tv_paymentdays)

    TextView detailRewardDay;//回款天数
    @BindView(R.id.detail_ll_paymentdays)
    LinearLayout llPaymentdays;

    @BindView(R.id.detail_tv_profit)
    TextView detailTvProfit;//万元收益
    @BindView(R.id.detail_ll_profit)
    LinearLayout llProfit;

    @BindView(R.id.detail_tv_simpleinterest)
    TextView tvSimpleinterest;//单利
    @BindView(R.id.detail_ll_simpleinterest)
    LinearLayout llSimpleinterest;

    @BindView(R.id.detail_tv_compound)
    TextView tvCompound;//复利
    @BindView(R.id.detail_ll_compound)
    LinearLayout llCompound;

    @BindView(R.id.detail_tv_status)
    TextView tvStatus;

    @BindView(R.id.raise_amount)
    TextView raiseAmout;//众筹金额
    @BindView(R.id.detail_tv_city)
    TextView tvCity;//尘世

    @BindView(R.id.detail_tv_expect_yield_rate)
    TextView expect_yield_rate;//预期年化
    @BindView(R.id.detail_tv_sequence)
    TextView tvSequence;//期数

    @BindView(R.id.detail_tv_electronic_protocol)
    TextView tvProtocol;

    @BindView(R.id.paid_time)
    TextView tvPaidtime;
    @BindView(R.id.detail_ll_rate)
    LinearLayout detailLlRate;

    private String orderId, simpleYearRate, crowdfunding_id, sequence, orderStatus, flag;

    public static Intent newInstance(Context context, String flag, String orderId, String simpleYearRate, String crowdfunding_id, String orderStatus) {
        Intent intent = new Intent(context, InvestRecordDetailActivity.class);
        intent.putExtra("flag", flag);
        intent.putExtra("orderId", orderId);
        intent.putExtra("simpleYearRate", simpleYearRate);
        intent.putExtra("crowdfunding_id", crowdfunding_id);
        intent.putExtra("orderStatus", orderStatus);
        return intent;
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_revord_detail;
    }

    @Override
    protected void initView() {
        ToolBarManager.with(this, WMContent).setTitle("订单详情")
                .setTitleColor(R.color.black_alpha90)
                .setNavigationIcon(R.drawable.ic_nav_arrow_back)
                .setBackgroundColor(R.color.toolbar_bg_grey);

        crowdfunding_id = getIntent().getStringExtra("crowdfunding_id");
        orderId = getIntent().getStringExtra("orderId");
        simpleYearRate = getIntent().getStringExtra("simpleYearRate");
        orderStatus = getIntent().getStringExtra("orderStatus");
        flag = getIntent().getStringExtra("flag");
        if (!TextUtils.equals(flag, InvestRecordFragment.INVEST_PAYMENT)) {
            llPayment.setVisibility(View.GONE);
            llPaymentdate.setVisibility(View.GONE);
            llProfit.setVisibility(View.GONE);
            llSimpleinterest.setVisibility(View.GONE);
            llCompound.setVisibility(View.GONE);
            llPaymentdays.setVisibility(View.GONE);
            if (TextUtils.equals(flag, InvestRecordFragment.INVEST_COLLECT)) {
                if (TextUtils.equals(orderStatus, "0")) {
                    tvProtocol.setText("立即支付");//状态
                } else {
                    tvProtocol.setVisibility(View.GONE);
                }

            }

        } else {
            orderStatus = "";
        }


        RetrofitHome.getInstance()
                .getInternalApi()
                .getOrderDetail(AppData.getToken(), orderId)
                .compose(RxSchedulers.<NormalResponseB<InvestOrderDetailB>>toMain())
                .subscribe(new OnRequestV2Listener<InvestOrderDetailB>(this) {
                    @Override
                    public void onNext(NormalResponseB<InvestOrderDetailB> value) {
                        super.onNext(value);
                        if (value.getIsLogged() != Const.STATE_LOGIN) {
                            goLogin();
                            return;
                        }
                        InvestOrderDetailB bean = value.getData();

                        Glide.with(mContext).load(bean.getDefault_image()).crossFade().into(ivImage);

                        tvStatus.setText(bean.getOrder_status_msg());//状态
                        setOrdetStatus();
                        tvOrderCode.setText("订单编号  " + bean.getOrder_id());//编号
                        tvTitle.setText(bean.getTitle());//标题
                        sequence = bean.getSequence();
                        tvSequence.setText("第" + bean.getSequence() + "期");//期数

                        raiseAmout.setText(StringUtil.changeMoneyToWan(bean.getRaise_amount()));//众筹金额
                        tvCity.setText(bean.getCity());//城市
                        expect_yield_rate.setText(bean.getExpect_yield_rate() + "%以上");//预期年化

                        //起息中

                        tvPrincipal.setText(bean.getOrder_amount() + "元");//投资本金
                        tvPaydate.setText(bean.getPaid_time());//支付时间
                        if (TextUtils.equals(flag, InvestRecordFragment.INVEST_PAYMENT)) {
                            MyViewsUtils.hideAllViews(detailLlRate);//特殊处理
                            //已回款
                            tvPrincipal.setText(bean.getOrder_amount() + "元");//投资本金
                            tvPayment.setText(bean.getReward_amount() + "元");//回款金额
                            tvPaydate.setText(bean.getPaid_time());//支付时间
                            tvPaymentdate.setText(bean.getSale_date());//回款时间
                            detailRewardDay.setText(bean.getReward_day() + "天");//回款天数
                            detailTvProfit.setText(bean.getWan_yield() + "元");//万元收益
                            tvSimpleinterest.setText(simpleYearRate + "%");//单利
                            tvCompound.setText(bean.getYield_rate() + "%");//复利
                        }
                    }
                });
    }

    private void setOrdetStatus() {
        if (TextUtils.isEmpty(orderStatus)) {
            return;
        }
        tvStatus.setText(TextUtils.equals(orderStatus, "0") ? "未支付" : "已支付");
    }

    @OnClick(R.id.detail_tv_car)
    void clickToCarDetail() {//查看车辆详情
        if (MyViewsUtils.isFastDoubleClick()) return;
//        startActivity(ProductDetailActivity.newInstance(mContext, crowdfunding_id, sequence));
        startActivity(ProductDetailActivity.newInstance(mContext, crowdfunding_id, sequence));
    }


    @OnClick(R.id.detail_tv_electronic_protocol)
    void clickToElectron() { //电子协议||立即支付
        //募集中的立即支付
        if (MyViewsUtils.isFastDoubleClick()) return;
        if (TextUtils.equals(flag, InvestRecordFragment.INVEST_COLLECT)) {
            if (TextUtils.equals(orderStatus, "0")) {
                rechargeSuccess();
            }
            return;
        }

        //需要读取权限
        new RxPermissions(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            getAgreement();
                        } else {
                            showOpenSettingDialog();
                        }
                    }
                });
//        String url = BuildConfig.HOST + "Wap/Crowdfunding/agreement/order/" + orderId;
//        startActivity(NormalWebActivity.newInstance(mContext, url, "悟空车物权众筹服务协议"));
    }

    private void getAgreement() {
        RetrofitHome.getInstance()
                .getInternalApi()
                .getAgreement(AppData.getToken(), orderId)
                .compose(RxSchedulers.<AgreementB>toMain())
                .subscribe(new OnRequestListener<AgreementB>(this) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    public void onNext(AgreementB value) {
                        super.onNext(value);
                        if (TextUtils.isEmpty(value.getAgreement_url())) return;
                        startActivity(PDFViewActivity.newIntent(mContext, "悟空车物权募集服务协议", value.getAgreement_url()));
                    }
                });
    }

    private void showOpenSettingDialog() {
        CustomDialogCenter.getInstance().showPermissionTipDialog(mContext, "没有此权限，APP将无法正常访问电子协议!");
    }

    /**
     * 充值成功
     */
    private void rechargeSuccess() {
        //余额不足的情况下，1.提交订单 2.充值 3.再次发起支付请求
        RetrofitHome.getInstance()
                .getInternalApi()
                .pay(AppData.getToken(), orderId)
                .compose(RxSchedulers.<RedirectContentB>toMain())
                .subscribe(new OnRequestListener<RedirectContentB>(((BaseActivity) mContext)) {
                    @Override
                    protected String getProgressBarContent() {
                        return "付款中...";
                    }

                    @Override
                    public void onNext(RedirectContentB value) {

                        //投资记录重新付款，余额不足跳充值界面
                        if (TextUtils.equals(value.getMsg(), "余额不足，无法支付订单")) {
                            WMToast.normal("余额不足，请充值");
                            mContext.startActivity(RechargeActivity.newInstance(mContext));
                            return;
                        }
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_FAILED) return;
                        mContext.startActivity(PayActivity.newInstance(mContext, value.getRedirect_content(), "支付", orderId));

                    }
                });
    }
}
